package com.dingdayu.club.admin;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.dingdayu.club.admin.adapter.EventListAdapter;
import com.dingdayu.club.admin.adapter.MemberAdapter;
import com.dingdayu.club.admin.api.GetClubInfo;
import com.dingdayu.club.admin.api.GetEventList;
import com.dingdayu.club.admin.api.GetMemberList;
import com.dingdayu.club.admin.api.LoginApi;
import com.dingdayu.club.admin.common.util.HttpUtils;
import com.dingdayu.club.admin.common.util.NetUtil;
import com.dingdayu.club.admin.common.util.SharePreferenceUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.kymjs.kjframe.KJBitmap;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    public static MainActivity mainActivity;
    public static GetClubInfo getClubInfo;
    public static GetMemberList getMemberList;
    public static GetEventList getEventList;

    public static TextView TuserName;
    public static ImageView TuserImage;
    public static TextView TuserEmail;
    public static ListView TlistView;
    public static TextView TtopView;

    public static Toolbar toolbar;

    public static String[][] MemberList;

    private SimpleAdapter simpleAdapter;
    public static final String TAG = MainActivity.class.getName();
    public static SharePreferenceUtil spU;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mainActivity = this;
        getClubInfo = new GetClubInfo();
        getMemberList = new GetMemberList();
        getEventList = new GetEventList();
        spU = new SharePreferenceUtil(LoginApi.USER_INFO_FILE);

         TuserName = (TextView)findViewById(R.id.userName);
         TuserEmail = (TextView)findViewById(R.id.userEmail);
         TuserImage =  (ImageView)findViewById(R.id.userImage);
         //TlistView = (ListView)findViewById(R.id.listView);
        //RelativeLayout lin = (RelativeLayout)findViewById(R.id.activity_main).findViewById(R.id.bar_main);
        TlistView = (ListView)findViewById(R.id.listView);
        TtopView = (TextView)findViewById(R.id.textView3);

        //检查用户登录
        int ClubID = spU.getClubID();
        if(ClubID == 0){
            Intent intent = new Intent(MainActivity.this,
                    LoginActivity.class);
            startActivity(intent);
        }

        //顶部栏
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("成员列表");
        setSupportActionBar(toolbar);

        //浮动按钮
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show();
                Intent intent = new Intent(MainActivity.this,
                        NoticeActivity.class);
                startActivity(intent);
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        //初始化侧边栏
        initNavigation();
        //网络监测
        if (!NetUtil.isNetConnected(this)) {
            new AlertDialog.Builder(this).setTitle("网络错误").setMessage("请开启网络后重试").setPositiveButton("确定",null).show();
        }else {
            //初始化第一个主页
            UpdateMemberListTask updateMemberList = new UpdateMemberListTask();
            updateMemberList.execute("");
        }


    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        TtopView.setText("");
        TlistView.setAdapter(null);

        if (id == R.id.nav_camara) {
            // Handle the camera action
            toolbar.setTitle("成员列表");
            //网络监测
            if (!NetUtil.isNetConnected(this)) {
                new AlertDialog.Builder(this).setTitle("网络错误").setMessage("请开启网络后重试").setPositiveButton("确定",null).show();
                return true;
            }else {
                UpdateMemberListTask updateMemberList = new UpdateMemberListTask();
                updateMemberList.execute("");
            }

        } else if (id == R.id.nav_gallery) {

            toolbar.setTitle("活动列表");
            //网络监测
            if (!NetUtil.isNetConnected(this)) {
                new AlertDialog.Builder(this).setTitle("网络错误").setMessage("请开启网络后重试").setPositiveButton("确定",null).show();
                return true;
            }else {
                UpdateEventListTask updateEventList = new UpdateEventListTask();
                updateEventList.execute("");
            }

        }  else if (id == R.id.nav_manage) {
            Intent intent = new Intent(MainActivity.this,
                    SettingsActivity.class);
            startActivity(intent);

        } else if (id == R.id.nav_share) {
            spU.remove("corp_id");
            Intent intent = new Intent(MainActivity.this,
                    LoginActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_send) {
            System.exit(0);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    /**
     * 监听返回--是否退出程序
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        boolean flag = true;
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 是否退出应用
            Exit(this);
        } else if (keyCode == KeyEvent.KEYCODE_MENU) {
            // 展示快捷栏&判断是否登录

        } else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
            // 展示搜索页
        } else {
            flag = super.onKeyDown(keyCode, event);
        }
        return flag;
    }

    /**
     * 退出程序
     *
     * @param cont
     */
    public static void Exit(final Context cont) {
        AlertDialog.Builder builder = new AlertDialog.Builder(cont);
        builder.setIcon(android.R.drawable.ic_dialog_info);
        builder.setTitle("退出应用");
        builder.setPositiveButton("点击退出",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        // 退出
                        try {
                            System.exit(0);
                        } catch (Exception e) {	}
                    }
                });
        builder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.show();
    }

    public void initNavigation(){
        //网络监测
        if (!NetUtil.isNetConnected(this)) {
            new AlertDialog.Builder(this).setTitle("网络错误").setMessage("请开启网络后重试").setPositiveButton("确定",null).show();
            return;
        }else {
            //getClubInfo.get();
            int ClubID = spU.getClubID();
            UpdateTask updateTask = new UpdateTask();
            updateTask.execute(String.valueOf(ClubID));
        }

    }

    //更新头像
    public static void dispalyLogo(String img_url){
        KJBitmap kjb = new KJBitmap();
        if(img_url != "") {
            Log.i("Main",img_url);
            kjb.display(TuserImage, img_url + "?imageView2/1/w/150/h/150");
        }
    }

    /**
     * 更新Event
     */
    public class UpdateEventListTask extends  AsyncTask<String, Integer, String[][]>{

        @Override
        protected String[][] doInBackground(String... params) {
            publishProgress(0);
            String[][] data = getEventList.get();
            publishProgress(100);
            return data;
        }

        protected void onProgressUpdate(Integer... progress) {
            //TtextView3.setText("loading..." + progress[0] + "%");
        }

        protected void onPostExecute(String[][] data) {
            ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

            // 循环遍历所有的歌节点 <song>
            for (int i = 0; i < data.length; i++) {
                // 新建一个 HashMap
                HashMap<String, String> map = new HashMap<String, String>();
                //每个子节点添加到HashMap关键= >值
                map.put("name",data[i][0]);
                map.put("star_time", data[i][1]);
                map.put("end_time", data[i][2]);
                map.put("count", data[i][3]);

                // HashList添加到数组列表
                songsList.add(map);
            }
            EventListAdapter adapter=new EventListAdapter(MainActivity.this, songsList);
            TlistView.setAdapter(adapter);
        }

    }


    /**
     * 更新Member
     */
    public class UpdateMemberListTask extends  AsyncTask<String, Integer, String[][]>{

        @Override
        protected String[][] doInBackground(String... params) {
            publishProgress(0);
            String[][] data = getMemberList.get();
            publishProgress(100);
            return data;
        }

        protected void onProgressUpdate(Integer... progress) {
            //TtextView3.setText("loading..." + progress[0] + "%");
        }

        protected void onPostExecute(String[][] data) {
            ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

            if(data != null){
                // 循环遍历所有的歌节点 <song>
                for (int i = 0; i < data.length; i++) {
                    // 新建一个 HashMap
                    HashMap<String, String> map = new HashMap<String, String>();
                    //每个子节点添加到HashMap关键= >值
                    map.put("name",data[i][6]);
                    map.put("cost", data[i][4]);
                    map.put("school", data[i][12]);
                    map.put("college", data[i][13]);
                    map.put("major", data[i][14]);
                    map.put("image", data[i][8]);

                    // HashList添加到数组列表
                    songsList.add(map);
                }
                MemberAdapter adapter=new MemberAdapter(MainActivity.this, songsList);
                TlistView.setAdapter(adapter);
            }else{
                //Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show();
                TtopView.setText("暂无数据");
                return;
            }
        }

    }

    /**
     * 启动一个现场进行认证
     */
    public class UpdateTask extends AsyncTask<String, Integer, HashMap<String, String>> {

        @Override
        protected HashMap<String, String> doInBackground(String... params) {
            publishProgress(0);
            HashMap<String, String> hm = new HashMap<String, String>();

            try {
                HashMap<String, String> params2 = new HashMap<String, String>();
                String ClubID = params[0];
                Log.e("ClubID", ClubID);
                params2.put("club_id", String.valueOf(ClubID));
                publishProgress(18);
                String t = HttpUtils.submitPostData("http://corp.xyser.com/Home/Api/getClubInfo", params2, "utf-8");
                Log.e("t", t);
                try {
                    publishProgress(80);
                    JSONObject jsonObj = new JSONObject(t);
                    int code = jsonObj.getInt("code");
                    String msg = jsonObj.getString("msg");
                    if (code == 302) {
                        // new AlertDialog.Builder(LoginActivity.loginactivity).setTitle(msg).setMessage("请重试").setPositiveButton("确定", null).show();
                        return hm;
                    }

                    if (code == 200) {
                        JSONObject data = jsonObj.getJSONObject("data");

                        hm.put("school",data.getString("school")) ;
                        hm.put("name",data.getString("name")) ;
                        hm.put("logo_img",data.getString("logo_img")) ;
                        hm.put("qrcode_file",data.getString("qrcode_file")) ;
                        hm.put("summary",data.getString("summary")) ;
                        hm.put("levl",data.getString("levl")) ;
                        hm.put("type", data.getString("type")) ;
                        publishProgress(85);
                        return hm;
                    }
                }catch (JSONException e) {
                    //new AlertDialog.Builder(LoginActivity.loginactivity).setTitle("服务器返回错误").setMessage("请稍后重试").setPositiveButton("确定",null).show();
                    Log.e("LoginAPI", "返回数据解析错误" + e.getMessage());
                    //login_ret = false;
                    //e.printStackTrace();
                    return null;
                }
            } catch (Exception e) {
                return null;
            }
            publishProgress(100);
            return null;
        }

        protected void onProgressUpdate(Integer... progress) {
            //TtextView3.setText("loading..." + progress[0] + "%");
        }

        protected void onPostExecute(HashMap<String, String> result) {
            if (result != null) {
                String img_url = result.get("logo_img");
                String name = result.get("name");
                String school = result.get("school");
                String type = result.get("type");
                Log.i("MainImg",img_url);

                TuserName = (TextView)findViewById(R.id.userName);
                TuserEmail = (TextView)findViewById(R.id.userEmail);
                TuserImage =  (ImageView)findViewById(R.id.userImage);

                dispalyLogo(img_url);

                TuserName.setText(name);
                TuserEmail.setText(school + " " + type);
            } else {
                Log.i("Main","数据错误");
            }
        }

        protected void onPreExecute() {
        }

        protected void onCancelled() {
            //mProgressBar.setProgress(0);
        }
    }
}
